package com.june.p2p;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Producer {
	
	private static final String QUEUE_NAME = "testQueue";

	public static void main(String[] args) {
		
		// 创建一个连接工厂 ConnectionFactory
		// user/password/url: admin/admin/tcp://localhost:61616
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				ActiveMQConnectionFactory.DEFAULT_USER, 
				ActiveMQConnectionFactory.DEFAULT_PASSWORD,
				ActiveMQConnectionFactory.DEFAULT_BROKER_URL);
		
		Connection connection = null;
		Session session = null;
		MessageProducer producer = null;
		
		try {			
			// 从连接工厂得到一个连接 Connection
			connection = connectionFactory.createConnection();
			// 通过连接来建立一个会话 Session
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
			// 创建消息队列
			Queue queue = session.createQueue(QUEUE_NAME);
			// 创建消息生产者
			producer = session.createProducer(queue);
			System.out.println("开始发送消息......");
			for (int i = 0; i < 10; i++) {			
				TextMessage message = session.createTextMessage("Hello P2P JMS text" + i);  
				producer.send(message);
			}
			System.out.println("发送消息完毕！");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {			
			try {
				if (producer != null) {					
					producer.close();
				}
				if (session != null) {					
					session.close();
				}
				if (connection != null) {
					connection.close();
				}
			} catch (JMSException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
